package com.ckh.springboot.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ckh.springboot.common.Constants;
import com.ckh.springboot.common.Result;
import com.ckh.springboot.controller.dto.UserDTO;
import com.ckh.springboot.controller.dto.UserPasswordDTO;
import com.ckh.springboot.entity.Goods;
import com.ckh.springboot.entity.JoinClass;
import com.ckh.springboot.entity.SysClass;
import com.ckh.springboot.mapper.UserMapper;
import com.ckh.springboot.service.IJoinClassService;
import com.ckh.springboot.service.ISysClassService;
import com.ckh.springboot.utils.TokenUtils;
import com.ckh.springboot.vo.UserVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ckh.springboot.service.IUserService;
import com.ckh.springboot.entity.User;

import org.springframework.web.bind.annotation.RestController;
import sun.awt.geom.AreaOp;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ckh
 * @since 2022-04-04
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "http://localhost:9528")
public class UserController {


    @Resource
    private IUserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ISysClassService sysClassService;

    @Resource
    private IJoinClassService joinClassService;

    @PostMapping("/register")
    public Result save(@RequestBody User user) {

        String studentId = user.getStudentId();
        String username = user.getName();
        String password = user.getPassword();
        String identity = user.getIdentity();
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password) || StrUtil.isBlank(studentId) || StrUtil.isBlank(identity)) {
            return Result.error(Constants.CODE_400, "参数错误,信息不能为空!");
        }
        //根据学号查询学号是否存在
        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getStudentId, user.getStudentId()));
        if(ObjectUtils.isNotEmpty(one)){
            return Result.error(Constants.CODE_400, "该学号已存在!");
        }
        return Result.success(userService.save(user));
    }

    @GetMapping("/login")
//    public Result login(@RequestBody User user) {
    public Result login(@RequestParam String studentId,@RequestParam  String password) {
        //返回
        UserVo userVo = new UserVo();
        //根据学号和密码查询用户
        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getStudentId, studentId)
                .eq(User::getPassword, password));
        // if(ObjectUtils.isEmpty(one)){
        //     return Result.error(Constants.CODE_400, "学号或密码错误!");
        // }
        if(ObjectUtils.isEmpty(one)){
            return Result.error(Constants.CODE_400, "账号或密码错误!");
        }
        
        //返回个人信息
        userVo.setUser(one);

        // 根据身份返回不同数据
        if ("admin".equals(studentId)) {  // 管理员
            // 管理员不需要额外数据
            return Result.success(userVo);
        } else if ("1".equals(one.getIdentity())) {  // 教师
            // 获取该教师的班级信息等
            List<SysClass> teacherClasses = sysClassService.list(
                Wrappers.<SysClass>lambdaQuery()
                    .eq(SysClass::getUserId, one.getId())  // 使用userId字段
            );
            userVo.setSysClassList(teacherClasses);
        } else {  // 学生
            // 获取学生已加入的班级
            List<SysClass> list = sysClassService.list(
                Wrappers.<SysClass>lambdaQuery()
                    .eq(SysClass::getClockStatus, 1)
            );
            List<SysClass> studentClasses = new ArrayList<>();
            for (SysClass sysClass : list) {
                List<JoinClass> joinClasses = joinClassService.list(
                    Wrappers.<JoinClass>lambdaQuery()
                        .eq(JoinClass::getClassId, sysClass.getId())
                        .eq(JoinClass::getUserId, one.getId())
                );
                for (JoinClass joinClass : joinClasses) {
                    if(sysClass.getId() == joinClass.getClassId()){
                        studentClasses.add(sysClass);
                    }
                }
            }
            userVo.setSysClassList(studentClasses);
        }

        // //查询已加入多少个班级需要打卡
        // List<SysClass> list = sysClassService.list(Wrappers.<SysClass>lambdaQuery().eq(SysClass::getClockStatus,1));
        // List<SysClass> list2 = new ArrayList<>();

        // for (SysClass sysClass : list) {
        //     List<JoinClass> list1 = joinClassService.list(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getClassId, sysClass.getId())
        //             .eq(JoinClass::getUserId, one.getId()));
        //     for (JoinClass joinClass : list1) {
        //         if(sysClass.getId()==joinClass.getClassId()){
        //             list2.add(sysClass);
        //         }
        //     }
        // }
        // userVo.setSysClassList(list2);

        return Result.success(userVo);
    }

    /**
     * Description: a
     * 请假时选择老师
     * @author: luoCan
     */
    @GetMapping("/getTeacherList")
    public Result getTeacherList() {
        //获取所有老师
        List<User> list = userService.list(Wrappers.<User>lambdaQuery().eq(User::getIdentity, 1));
        return Result.success(list);
    }

    /**
     * Description: a
     * 获取班级打卡情况
     * @author: luoCan
     */
    @GetMapping("/getStudentClockInfo")
    public Result getStudentClockInfo(@RequestParam Integer classId) {
        return Result.success(userService.getStudentClockInfo(classId));
    }

    /**
     * Description:a
     * 后台获取用户列表
     * @param null:
     * @author: luoCan
     */
    @GetMapping("/getUserList")
    public Result getUserList(String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<User> page = userService.getUserList(new Page<>(pageNum, pageSize), name);
        return Result.success(page);
    }

    /**
     * Description:a
     * 后台用户修改
     * @param null:
     * @author: luoCan
     */
    @PostMapping("/updateUserById")
    public Result updateUserById(@RequestBody User user) {
        return Result.success(userService.updateById(user));
    }

    /**
     * Description:a
     * 后台用户删除
     * @param null:
     * @author: luoCan
     */
    @PostMapping("/deleteUserById")
    public Result deleteUserById(@RequestBody User user) {
        return Result.success(userService.removeById(user));
    }


    // 新增或者更新
//    @PostMapping
//    public Result save(@RequestBody User user) {
//        return Result.success(userService.saveOrUpdate(user));
//        }
    /**
     * 修改密码
     * @param userPasswordDTO
     * @return
     */
    @PostMapping("/password")
    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
        userService.updatePassword(userPasswordDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
        }


    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
        }

    @GetMapping("/role/{role}")
    public Result findUsersByRole(@PathVariable String role) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role",role);
        List<User> list =  userService.list(queryWrapper);
        return Result.success(list);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
        }
    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }


    @GetMapping("/rank")
    public Map<String, Object> rankPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam String username) {
        pageNum = (pageNum - 1) * pageSize;
        username = "%" + username + "%";
        List<User> data = userMapper.selectPage(pageNum, pageSize, username);
        Map<String, Object> res = new HashMap<>();
        res.put("data", data);
        return res;
    }

    /**
     * 根据 id 返回student_id
     */
    @GetMapping("/getStudentId")
    public Result rankPage(@RequestParam Integer id) {
        System.out.println(id);
        Integer studentId = userMapper.getStudentId(id);
        return Result.success(studentId);
    }
}

